<template>
  <section class="padding">
    <el-card class="box-card">
      <el-form
        :inline="true"
        class="form-inline padding-top-sm flex align-center justify-between"
        size="mini"
        :model="searchCriteria"
      >
        <el-form-item label="预约提货时间">
          <!-- <el-date-picker
            v-model="earchTimer"
            type="datetimerange"
            align="right"
            unlink-panels
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="pickerOptions"
          /> -->
          <el-date-picker
            v-model="searchCriteria.startPickUpDate"
            align="right"
            type="datetime"
            placeholder="开始时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
          -
          <el-date-picker
            v-model="searchCriteria.endPickUpDate"
            align="right"
            type="datetime"
            placeholder="结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button type="primary" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="margin-top">
      <div class="flex align-center justify-between padding-bottom-sm">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[20, 40, 60, 80, 100]"
          :page-size="pageSize"
          layout="prev, pager, next, jumper, sizes,total"
          :total="pageTotal"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <div :inline="true" class="">
          <el-button
            size="mini"
            type="success"
            icon="el-icon-plus"
            @click="addSubmit"
          >
            预约提货
          </el-button>
        </div>
      </div>
      <el-table
        class="table-box"
        :border="true"
        :data="tableData"
        style="width: 100%"
        size="mini"
      >
        <el-table-column type="index" label="序号" />
        <!-- 遍历col -->
        <el-table-column
          v-for="column in tableColumns"
          show-overflow-tooltip
          :key="column.prop"
          :auto-fit="true"
          :fit-header="true"
          :prop="column.prop"
          :label="column.label"
        />

        <el-table-column
          show-overflow-tooltip
          :auto-fit="true"
          :fit-header="true"
          label="备注"
        >
          <template slot-scope="scope">
            <div>
              {{ scope.row.takeDeliveryOrderTypeStr }}
              <br
                v-if="scope.row.takeDeliveryOrderTypeStr && scope.row.sysRemark"
              />
              {{ scope.row.sysRemark }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          :auto-fit="true"
          :fit-header="true"
          prop="cdate"
          label="创建时间"
        />
        <el-table-column
          show-overflow-tooltip
          :auto-fit="true"
          :fit-header="true"
          prop="arrangementPickupDate"
          label="安排时间"
        />
        <el-table-column
          show-overflow-tooltip
          :auto-fit="true"
          :fit-header="true"
          prop="scoreGradeName"
          label="评价"
        />

        <el-table-column fixed="right" label="操作">
          <template slot-scope="scope">
            <el-tooltip
              v-if="
                scope.row.arrangementTakeDeliveryOfGoods != 1 &&
                  (scope.row.driverName === null || scope.row.driverName === '')
              "
              class="item margin-left-sm"
              effect="dark"
              content="删除"
              placement="top"
            >
              <i
                class="el-icon-close"
                style="font-size: large;"
                @click="operationList(scope.row, 'delete')"
              />
            </el-tooltip>
            <el-tooltip
              v-if="
                scope.row.arrangementPickupDate != null &&
                  scope.row.arrangementPickupDate != '' &&
                  (scope.row.driverName === null || scope.row.driverName === '')
              "
              class="item margin-left-sm"
              effect="dark"
              content="取消提货"
              placement="top"
            >
              <svg-icon
                class="operation-icon"
                name="return"
                style="font-size: large;"
                @click="operationList(scope.row, 'return')"
              />
            </el-tooltip>
            <el-tooltip
              class="item margin-left-sm"
              effect="dark"
              content="评价"
              placement="top"
            >
              <i
                class="el-icon-chat-dot-round"
                style="color: red;font-size: large;"
                @click="appraised(scope.row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog title="创建提货单" :visible.sync="addDialogFormVisible">
      <div class="dialog-section padding">
        <el-table
          ref="multipleTable"
          :data="addTableData"
          tooltip-effect="dark"
          style="width: 100%"
          size="mini"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="运单号" prop="waybillNo" width="120" />
          <el-table-column label="参考号" prop="referenceNo" width="120" />
          <el-table-column
            prop="customerTotalPackages"
            label="预报件数"
            width="120"
          />

          <el-table-column prop="customerActualWeight" label="预报重量（KG）" />
          <el-table-column prop="customerVolume" label="预报体积（CMB）" />
          <el-table-column prop="schedulePickupName" label="是否已预约" />
        </el-table>
        <el-form
          ref="addForm"
          :model="addForm"
          :rules="rules"
          size="mini"
          class="margin-top"
          label-width="90px"
        >
          <el-row>
            <el-col :span="8">
              <el-form-item prop="takeDeliveryOfGoodsCount">
                <div slot="label">件数:</div>
                <el-input
                  v-model="addForm.takeDeliveryOfGoodsCount"
                  autocomplete="off"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="takeDeliveryOfGoodsWeight">
                <div slot="label">重量(KG):</div>
                <el-input
                  v-model="addForm.takeDeliveryOfGoodsWeight"
                  autocomplete="off"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="takeDeliveryOfGoodsVolume">
                <div slot="label">体积(CMB):</div>
                <el-input
                  v-model="addForm.takeDeliveryOfGoodsVolume"
                  autocomplete="off"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item prop="appointmentPickupDate">
            <div slot="label">提货时间:</div>
            <el-date-picker
              v-model="addForm.appointmentPickupDate"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
              :picker-options="appointmentPickerOptions"
            />
          </el-form-item>
          <div
            class="text-right text-orange pointer padding-tb-sm"
            @click="addNewAdderss = true"
          >
            <span><i class="el-icon-plus" /> 新增提货地址</span>
          </div>
          <div v-if="addNewAdderss">
            <el-row>
              <el-col :span="12">
                <el-form-item prop="provinces">
                  <div slot="label">所在地区:</div>
                  <el-cascader
                    v-model="addressForm.provinces"
                    filterable
                    :options="cityOptions"
                    @change="cityHandleChange"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="address">
                  <div slot="label">详细地址:</div>
                  <el-input v-model="addressForm.address" autocomplete="off" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="linkMan">
                  <div slot="label">联系人:</div>
                  <el-input v-model="addressForm.linkMan" autocomplete="off" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="contactWay">
                  <div slot="label">手机号码:</div>
                  <el-input
                    v-model="addressForm.contactWay"
                    autocomplete="off"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item>
              <el-button type="primary" size="mini" @click="saveAddress">
                保存提货地址
              </el-button>
              <el-button type="primary" size="mini" @click="closeEdit">
                取消编辑
              </el-button>
            </el-form-item>
          </div>

          <el-form-item label="提货地址">
            <div class="padding-lr">
              <template v-for="(item, index) in addressList">
                <div
                  v-if="
                    showMoreAddress || (!showMoreAddress && item.defaultValue)
                  "
                  :key="index"
                  class="address-item padding-lr margin-bottom-sm"
                  :class="{ 'address-active': item.defaultValue }"
                  @click="selectAddress(index)"
                >
                  <el-row>
                    <el-col :span="4">
                      {{ item.linkMan }}
                    </el-col>
                    <el-col :span="14">
                      {{
                        item.state +
                          item.city +
                          item.area +
                          item.street +
                          item.address
                      }}
                    </el-col>
                    <el-col :span="6">
                      {{ item.contactWay }}
                    </el-col>
                  </el-row>
                </div>
              </template>
            </div>
            <div class="text-sm" @click="showMoreAddress = !showMoreAddress">
              <span v-if="showMoreAddress">
                收起地址
                <i class="el-icon-arrow-up" />
              </span>
              <span v-else>
                更多地址
                <i class="el-icon-arrow-down" />
              </span>
            </div>
          </el-form-item>

          <el-row>
            <el-col :span="12">
              <el-form-item label="备用手机">
                <el-input
                  v-model="addForm.takeDeliveryOfGoodsLinkPhoneSpare"
                  autocomplete="off"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="运单类型" prop="shippwayType">
                <el-select
                  v-model="addForm.takeDeliveryOrderType"
                  placeholder="请选择运单类型"
                >
                  <el-option
                    v-for="(item, value) in publicData.takeDeliveryOrderTypeMap"
                    :key="value"
                    :label="$t('waybill.' + item)"
                    :value="value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <div class="text-red text-center">
            温馨提示：如需取消提货，请及时电话通知我司销售人员，如司机已在途中，将产生返空费
          </div>
          <el-form-item label="备注">
            <el-input
              v-model="addForm.sysRemark"
              type="textarea"
              autocomplete="off"
            />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeAddDialogForm">取 消</el-button>
        <el-button type="primary" @click="submitAddDialogForm">
          确 定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="评价" :visible.sync="appraisedDialogFormVisible">
      <div class="dialog-section padding">
        <el-row class="appraised-row">
          你对这次提货服务还满意吗？
        </el-row>
        <el-form
          ref="appraisedForm"
          :model="appraisedForm"
          :rules="rules"
          size="mini"
          label-width="90px"
        >
          <el-row class="appraised-row">
            <el-col :span="2">服务态度</el-col>
            <el-col :span="22">
              <el-rate
                v-model="appraisedForm.scoreGrade"
                :texts="texts"
                text-color="#F7BA2A"
                show-text
                @change="scoreGradeChange"
              />
            </el-col>
          </el-row>
          <el-row class="appraised-row">
            <el-col :span="2">提货时效</el-col>
            <el-col :span="22">
              <el-rate
                v-model="appraisedForm.scoreTakeDeliveryOfGood"
                :texts="texts"
                text-color="#F7BA2A"
                show-text
              />
            </el-col>
          </el-row>
          <el-row class="appraised-row">
            <template v-for="(item, index) in appraiseList">
              <el-button
                v-if="item.isDiff && differenceAppraise"
                :key="index"
                type="warning"
                size="small"
                :class="{
                  'el-button-isval': item.isFlag,
                  'el-button-isval-f': !item.isFlag
                }"
                @click="selectAppraisedLabel(index)"
              >
                {{ item.name }}
              </el-button>
              <el-button
                v-if="!item.isDiff && goodsAppraise"
                :key="index"
                type="warning"
                size="small"
                :class="{
                  'el-button-isval': item.isFlag,
                  'el-button-isval-f': !item.isFlag
                }"
                @click="selectAppraisedLabel(index)"
              >
                {{ item.name }}
              </el-button>
            </template>
          </el-row>
          <el-row class="appraised-row">
            <el-input
              v-model="appraisedForm.appraisedContent"
              type="textarea"
              autocomplete="off"
            />
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeAppraisedDialogForm">取 消</el-button>
        <el-button type="primary" @click="submitAppraisedDialogForm">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  pageTakeDeliveryOfGoods,
  listPage,
  createTakeDeliveryOfGoods,
  appraisedTakeDeliveryOfGoods,
  deleteTakeDeliveryOfGoods,
  cancleTakeDeliveryOfGoods
} from '@/api/waybill'
import { getPcas } from '@/utils/city-pcas.js'
import {
  customerpickupadderssList,
  customerpickupadderssSave
} from '@/api/myProfile'
import { clone } from '@/utils/clone'
import moment from 'moment'
import 'moment/locale/zh-cn'
moment.locale('zh-cn')

export default {
  name: 'PickupInformation',
  components: {},
  data() {
    return {
      cityOptions: getPcas(),
      addNewAdderss: false,
      showMoreAddress: false,
      searchCriteria: {
        startPickUpDate: '',
        endPickUpDate: ''
      },
      appointmentPickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7 // 如果没有后面的-8.64e7就是不可以选择今天的
        },
        selectableRange: (() => {
          const data = new Date()
          const hour = data.getHours()
          const minute = data.getMinutes()
          const second = data.getSeconds()
          return [`${hour}:${minute}:${second} - 23:59:59`]
        })(),
        shortcuts: [
          {
            text: '5分钟后',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() + 300 * 1000)
              picker.$emit('pick', date)
            }
          },
          {
            text: '10分钟后',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() + 600 * 1000)
              picker.$emit('pick', date)
            }
          },
          {
            text: '30分钟后',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() + 1800 * 1000)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      pickerOptions: {
        shortcuts: [
          {
            text: '一天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '三天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      earchTimer: [],
      currentPage: 1,
      pageSize: 20,
      pageTotal: 0,
      tableColumns: [
        { prop: 'appointmentPickupDate', label: '预约提货时间' },
        { prop: 'pickUpGoodsNum', label: '提货单号' },
        { prop: 'takeDeliveryOfGoodsCount', label: '件数' },
        { prop: 'takeDeliveryOfGoodsVolume', label: '体积' },
        { prop: 'takeDeliveryOfGoodsWeight', label: '重量' },
        { prop: 'takeDeliveryOfGoodsProvince', label: '省' },
        { prop: 'takeDeliveryOfGoodsCity', label: '市' },
        { prop: 'takeDeliveryOfGoodsArea', label: '区' },
        { prop: 'takeDeliveryOfGoodsStreet', label: '街道' },
        { prop: 'takeDeliveryOfGoodsAddress', label: '详细地址' },
        { prop: 'takeDeliveryOfGoodsLinkMan', label: '提货联系人' },
        { prop: 'takeDeliveryOfGoodsLinkPhone', label: '联系人手机' },
        { prop: 'takeDeliveryOfGoodsLinkPhoneSpare', label: '备用手机' },
        { prop: 'driverName', label: '司机姓名' },
        { prop: 'driverPhone', label: '司机手机' },
        { prop: 'licensePlate', label: '车牌' }
      ],
      takeDeliveryOrderTypeMap: {},
      tableData: [],
      addDialogFormVisible: false,
      addFormLabelWidth: '120px',
      addForm: {
        takeDeliveryOfGoodsStreet: '',
        takeDeliveryOfGoodsAddress: '',
        takeDeliveryOfGoodsProvince: '',
        takeDeliveryOfGoodsCity: '',
        takeDeliveryOfGoodsArea: '',
        takeDeliveryOfGoodsLinkMan: '',
        takeDeliveryOfGoodsLinkPhone: '',
        waybills: [],
        takeDeliveryOfGoodsCount: '',
        takeDeliveryOfGoodsWeight: '',
        takeDeliveryOfGoodsVolume: '',
        appointmentPickupDate: '',
        takeDeliveryOfGoodsLinkPhoneSpare: '',
        sysRemark: '',
        shippwayType: ''
      },
      addTableData: [],
      multipleSelection: [],
      addressList: [],
      addressForm: {
        street: '',
        address: '',
        state: '',
        city: '',
        area: '',
        provinces: []
      },
      rules: {
        takeDeliveryOfGoodsCount: [
          { required: true, message: '请填写件数', trigger: 'blur' }
        ],
        takeDeliveryOfGoodsWeight: [
          { required: true, message: '请填写重量', trigger: 'blur' }
        ],
        takeDeliveryOfGoodsVolume: [
          { required: true, message: '请填写体积', trigger: 'blur' }
        ],
        appointmentPickupDate: [
          { required: true, message: '请选择提货时间', trigger: 'change' }
        ],
        takeDeliveryOrderType: [
          { required: true, message: '请选择运单类型', trigger: 'change' }
        ]
      },
      appraisedDialogFormVisible: false,
      appraisedForm: {
        id: '',
        scoreTakeDeliveryOfGood: 0,
        scoreGrade: 0,
        appraisedContent: '',
        appraisedLabel: '' //  存储格式1,2,3,4
      },
      texts: [
        '非常不满意，各方面都差',
        '不满意，比较差',
        '一般，还需改善',
        '比较满意，仍可改善',
        '非常满意，无可挑剔'
      ],
      differenceAppraise: true,
      appraiseList: [],
      goodsAppraise: false
    }
  },
  computed: {
    ...mapGetters(['publicData'])
  },
  watch: {
    'addForm.appointmentPickupDate': {
      handler(newValue, oldValue) {
        if (newValue) {
          const date = new Date()
          const nowDate = moment(date).format('HH:mm:ss')
          if (
            moment(date).format('yyyy-MM-DD') ===
            moment(newValue).format('yyyy-MM-DD')
          ) {
            console.log('当前时间', nowDate)
            this.appointmentPickerOptions.selectableRange = `${nowDate}-23:59:59`
          } else {
            this.appointmentPickerOptions.selectableRange = `00:00:00-23:59:59`
          }
        }
      },
      // deep: true,
      immediate: true
    }
  },
  mounted() {
    this.queryList()
    // console.log(11, this.cityOptions)
    for (let i of this.cityOptions) {
      for (let v of i.children) {
        for (let k of v.children) {
          k.children.push({
            label: '暂不选择',
            value: ''
          })
        }
      }
    }
    // this.initAppraisedList("")
  },
  methods: {
    initAppraisedList(val) {
      if (this.publicData.differenceAppraisedLabelMap) {
        for (const key in this.publicData.differenceAppraisedLabelMap) {
          if (val) {
            let values = val.split(',')
            console.log('values', values, values.indexOf(key))
            if (values.indexOf(key) != -1) {
              this.appraiseList.push({
                value: key,
                name: this.publicData.differenceAppraisedLabelMap[key],
                isFlag: true,
                isDiff: true
              })
            } else {
              this.appraiseList.push({
                value: key,
                name: this.publicData.differenceAppraisedLabelMap[key],
                isFlag: false,
                isDiff: true
              })
            }
          } else {
            this.appraiseList.push({
              value: key,
              name: this.publicData.differenceAppraisedLabelMap[key],
              isFlag: false,
              isDiff: true
            })
          }
        }
      }

      if (this.publicData.goodsAppraisedLabelMap) {
        for (const key in this.publicData.goodsAppraisedLabelMap) {
          if (val) {
            let values = val.split(',')
            console.log('values', values, values.indexOf(key))
            if (values.indexOf(key) != -1) {
              this.appraiseList.push({
                value: key,
                name: this.publicData.goodsAppraisedLabelMap[key],
                isFlag: true,
                isDiff: false
              })
            } else {
              this.appraiseList.push({
                value: key,
                name: this.publicData.goodsAppraisedLabelMap[key],
                isFlag: false,
                isDiff: false
              })
            }
          } else {
            this.appraiseList.push({
              value: key,
              name: this.publicData.goodsAppraisedLabelMap[key],
              isFlag: false,
              isDiff: false
            })
          }
        }
      }
    },
    async queryList() {
      this.searchCriteria.pageSize = this.pageSize
      this.searchCriteria.currentPage = this.currentPage

      // if (this.earchTimer.length > 0) {
      //   this.searchCriteria.startPickUpDate = this.earchTimer[0]
      //   this.searchCriteria.endPickUpDate = this.earchTimer[1]
      // } else {
      //   this.searchCriteria.startPickUpDate = ''
      //   this.searchCriteria.endPickUpDate = ''
      // }
      // if(Date.parse(this.searchCriteria.endPickUpDate) < Date.parse(this.searchCriteria.startPickUpDate)) {
      //     this.$message.error("结束时间必须大于开始时间");
      // }

      const list = await pageTakeDeliveryOfGoods(this.searchCriteria)
      this.tableData = list.datas
      this.tableData.forEach(data => {
        if (data.scoreGrade != null) {
          data.scoreGradeName = data.scoreGrade + '星'
        }
        if (data.takeDeliveryOrderType) {
          //console.log(this.publicData.takeDeliveryOrderTypeMap[data.takeDeliveryOrderType]);
          data.takeDeliveryOrderTypeStr = this.$t(
            'waybill.' +
              this.publicData.takeDeliveryOrderTypeMap[
                data.takeDeliveryOrderType
              ]
          )
        }
      })

      this.pageTotal = list.count
      this.$store.dispatch('app/toggleDialog', false)
    },
    handleSizeChange(val) {
      this.$store.dispatch('app/toggleDialog', true)
      this.pageSize = val
      this.queryList()
    },
    handleCurrentChange(val) {
      this.$store.dispatch('app/toggleDialog', true)
      this.currentPage = val
      this.queryList()
    },
    onSubmit() {
      this.$store.dispatch('app/toggleDialog', true)
      this.currentPage = 1
      this.queryList()
    },
    onReset() {
      this.$store.dispatch('app/toggleDialog', true)
      this.searchCriteria = {
        startPickUpDate: '',
        endPickUpDate: ''
      }
      this.currentPage = 1
      this.queryList()
    },
    async addSubmit() {
      this.$store.dispatch('app/toggleDialog', true)
      const list = await listPage({ selfDelivered: 1, status: [10, 20] })
      //  console.log("list",list);
      for (let index = 0; index < list.datas.length; index++) {
        if (list.datas[index].schedulePickup == 1) {
          list.datas[index].schedulePickupName = '是'
        } else {
          list.datas[index].schedulePickupName = '否'
        }
      }
      this.addTableData = list.datas

      this.addressList = await customerpickupadderssList({})
      // console.log('addressList', this.addressList)
      this.addDialogFormVisible = true
      this.closeEdit()
      this.showMoreAddress = false
      this.$store.dispatch('app/toggleDialog', false)
    },
    //  关闭创建弹窗
    closeAddDialogForm() {
      this.addTableData = []
      this.addressList = []
      this.takeDeliveryOrderTypeMap = {}
      this.addForm = {
        takeDeliveryOfGoodsStreet: '',
        takeDeliveryOfGoodsAddress: '',
        takeDeliveryOfGoodsProvince: '',
        takeDeliveryOfGoodsCity: '',
        takeDeliveryOfGoodsArea: '',
        takeDeliveryOfGoodsLinkMan: '',
        takeDeliveryOfGoodsLinkPhone: '',
        waybills: [],
        takeDeliveryOfGoodsCount: '',
        takeDeliveryOfGoodsWeight: '',
        takeDeliveryOfGoodsVolume: '',
        appointmentPickupDate: '',
        takeDeliveryOfGoodsLinkPhoneSpare: '',
        takeDeliveryOrderType: '',
        sysRemark: '',
        shippwayType: ''
      }
      this.multipleSelection = []
      this.addressForm = {
        street: '',
        address: '',
        state: '',
        city: '',
        area: '',
        provinces: []
      }
      this.addDialogFormVisible = false
    },

    submitAddDialogForm() {
      this.$refs['addForm'].validate(valid => {
        if (valid) {
          this.checkAdderss()
        } else {
          //  console.log('error submit!!')
          return false
        }
      })
    },

    checkAdderss() {
      const waybills = []
      for (const i of this.multipleSelection) {
        const waybill = {
          waybillId: i.id,
          salesmanId: i.salesmanId,
          waybillNo: i.waybillNo
        }
        waybills.push(waybill)
      }

      if (this.addressList.length > 0) {
        const params = clone(this.addForm)
        let flag = false
        for (const data of this.addressList) {
          if (data.defaultValue === 1) {
            flag = true
            params.waybills = waybills
            params.takeDeliveryOfGoodsStreet = data.street
            params.takeDeliveryOfGoodsAddress = data.address
            params.takeDeliveryOfGoodsProvince = data.state
            params.takeDeliveryOfGoodsCity = data.city
            params.takeDeliveryOfGoodsArea = data.area
            params.takeDeliveryOfGoodsLinkMan = data.linkMan
            params.takeDeliveryOfGoodsLinkPhone = data.contactWay
          }
        }

        if (flag) {
          this.saveInfo(params)
        } else {
          this.$message.error('请选择提货地址！')
          return
        }
      } else {
        this.$message.error('请填写提货地址！')
        return
      }
    },

    //  提交提货单
    async saveInfo(params) {
      console.log('params :>> ', params)

      // return
      this.$store.dispatch('app/toggleDialog', true)
      const data = await createTakeDeliveryOfGoods(params)
      //  console.log("params",data);
      if (data.code === 200) {
        this.closeAddDialogForm()
        this.queryList()
      } else {
        this.$store.dispatch('app/toggleDialog', false)
        this.$message.error(data.message)
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      if (this.multipleSelection.length < 1) {
        this.addForm.takeDeliveryOfGoodsCount = 0
        this.addForm.takeDeliveryOfGoodsWeight = 0
        this.addForm.takeDeliveryOfGoodsVolume = 0
        return
      }
      let customerTotalPackages = 0
      let customerActualWeight = 0
      let customerVolume = 0
      for (const i of this.multipleSelection) {
        if (i.customerTotalPackages) {
          customerTotalPackages += i.customerTotalPackages
          this.addForm.takeDeliveryOfGoodsCount = customerTotalPackages
        }
        if (i.customerActualWeight) {
          customerActualWeight =
            (Number(customerActualWeight) * 1000 +
              Number(i.customerActualWeight) * 1000) /
            1000
          this.addForm.takeDeliveryOfGoodsWeight = customerActualWeight
        }
        if (i.customerVolume) {
          customerVolume =
            (Number(customerVolume) * 1000 + Number(i.customerVolume * 1000)) /
            1000
          this.addForm.takeDeliveryOfGoodsVolume = customerVolume
        }
      }
    },
    selectAddress(index) {
      for (const i of this.addressList) {
        i.defaultValue = 0
      }
      this.addressList[index].defaultValue = 1
    },
    cityHandleChange(val) {
      if (!val) return
      if (val[3] === '暂不选择') {
        val[3] = ''
      }
      for (let i of this.cityOptions) {
        for (let v of i.children) {
          for (let k of v.children) {
            for (let j of k.children) {
              if (j.label === '暂不选择') {
                j.label = ''
              }
            }
          }
        }
      }
      ;[
        this.addressForm.state,
        this.addressForm.city,
        this.addressForm.area,
        this.addressForm.street
      ] = val
      // console.log('this.addressForm: ', this.addressForm)
    },
    closeEdit() {
      this.addressForm = {
        linkMan: '',
        contactWay: '',
        address: '',
        state: '',
        city: '',
        area: '',
        street: '',
        provinces: []
      }
      this.addNewAdderss = false
    },
    //  提交地址
    async saveAddress() {
      this.$store.dispatch('app/toggleDialog', true)
      const params = this.addressForm
      params.defaultValue = 0
      const data = await customerpickupadderssSave(params)
      if (data.code === 200) {
        this.addressList = await customerpickupadderssList({})
        this.closeEdit()
      } else {
        this.$message.error(data.message)
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    async operationList(data, name) {
      switch (name) {
        case 'delete':
          this.$confirm('确定要删除吗？')
            .then(_ => {
              this.deleteTakeDeliveryOfGoods(data.id)
            })
            .catch(_ => {})
          break
        case 'return':
          this.$confirm('确定要取消提货吗？')
            .then(_ => {
              this.cancleTakeDeliveryOfGoods(data.id)
            })
            .catch(_ => {})
          break
      }
    },
    async deleteTakeDeliveryOfGoods(id) {
      //  删除
      this.$store.dispatch('app/toggleDialog', true)
      const { code, message } = await deleteTakeDeliveryOfGoods({ id: id })
      if (code === 200) {
        this.queryList()
      } else {
        this.$message.error(message)
        this.$store.dispatch('app/toggleDialog', false)
      }
    },
    async cancleTakeDeliveryOfGoods(id) {
      // 取消提货
      this.$store.dispatch('app/toggleDialog', true)
      const { code, message } = await cancleTakeDeliveryOfGoods({ id: id })
      if (code === 200) {
        this.queryList()
      } else {
        this.$message.error(message)
        this.$store.dispatch('app/toggleDialog', false)
      }
    },
    appraised(row) {
      // console.log("this is pingjia",row);
      // 初始化提交数据
      this.appraisedForm = {
        id: row.id,
        scoreTakeDeliveryOfGood: row.scoreTakeDeliveryOfGood,
        scoreGrade: row.scoreGrade,
        appraisedContent: row.appraisedContent,
        appraisedLabel: row.appraisedLabel // 存储格式1,2,3,4
      }
      this.appraiseList = []
      if (row.scoreGrade === 5) {
        this.goodsAppraise = true
        this.differenceAppraise = false
      } else {
        this.differenceAppraise = true
        this.goodsAppraise = false
      }
      this.initAppraisedList(row.appraisedLabel)
      this.appraisedDialogFormVisible = true
    },
    closeAppraisedDialogForm() {
      this.appraisedDialogFormVisible = false
    },
    // 提交评价
    async submitAppraisedDialogForm() {
      let appraisedLabelStr = ''
      this.appraiseList.forEach(data => {
        if (data.isFlag) {
          appraisedLabelStr += data.value + ','
        }
      })
      if (appraisedLabelStr !== '') {
        this.appraisedForm.appraisedLabel = appraisedLabelStr.substring(
          0,
          appraisedLabelStr.length - 1
        )
      }

      if (
        this.appraisedForm.scoreGrade === 0 ||
        this.appraisedForm.scoreTakeDeliveryOfGood === 0
      ) {
        this.$message.error('服务态度和提货时效必须评价')
        return
      }
      this.$store.dispatch('app/toggleDialog', true)
      const data = await appraisedTakeDeliveryOfGoods(this.appraisedForm)
      if (data.code === 200) {
        this.addressList = await customerpickupadderssList({})
        this.closeAppraisedDialogForm()
        this.queryList()
      } else {
        this.$message.error(data.data)
        this.$store.dispatch('app/toggleDialog', false)
      }
    },
    // 点击标签
    selectAppraisedLabel(index) {
      if (this.appraiseList[index].isFlag) {
        this.appraiseList[index].isFlag = false
      } else {
        this.appraiseList[index].isFlag = true
      }
    },
    // 点击评分
    scoreGradeChange(val) {
      if (val === 5) {
        this.goodsAppraise = true
        this.differenceAppraise = false
        this.appraiseList.forEach(data => {
          if (data.isDiff) {
            data.isFlag = false
          }
        })
      } else {
        this.goodsAppraise = false
        this.differenceAppraise = true
        this.appraiseList.forEach(data => {
          if (!data.isDiff) {
            data.isFlag = false
          }
        })
      }
    },
    async appointmentPickupDateCheck() {
      var arr = [];
      for (let i of this.multipleSelection) {
        if (arr.indexOf(i.loadingPort) < 0) {
          arr.push(i.loadingPort);
        }
      }
      if (arr.length<1){
        this.$message.error("请先选择运单");
        return;
      }
      const data = await appointmentPickupDateCheck({
        portList: arr,
        appointmentPickupDate: this.formData.appointmentPickupDate
      })
      if (data.code !== 200) {
        this.$message.error(res.message);
        this.addForm.appointmentPickupDate = "";
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-col {
  border-radius: 4px;
}

.pan-btn {
  font-size: 12px;
  //  color: #fff;
  width: 100%;
  text-align: center;
  color: #337ab7;
  padding: 14px 0;
  border-radius: 8px;
  border: none;
  outline: none;
  transition: 600ms ease all;
  position: relative;
  display: inline-block;
  cursor: pointer;

  &:hover {
    color: #30b08f;
    //  background: #ccc;

    &:before,
    &:after {
      background: #30b08f;
      width: 100%;
      transition: 600ms ease all;
    }
  }

  &:before,
  &:after {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    height: 2px;
    width: 0;
    transition: 400ms ease all;
  }

  &::after {
    right: inherit;
    top: inherit;
    left: 0;
    bottom: 0;
  }
}
.financial-title {
  color: rgba(0, 0, 0, 0.45);
  font-size: 16px;
  text-align: center;
}

.financial-title-money {
  color: #666;
  font-size: 20px;
  text-align: center;
}

.shadow {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.form-inline {
  .el-form-item--mini.el-form-item,
  .el-form-item--small.el-form-item {
    margin-bottom: 8px;
  }
}

.dialog-section {
  max-height: 600px;
  overflow-y: auto;

  .address-item {
    border: 1px solid #ccc;
  }

  .address-active {
    position: relative;
    border: 1px solid #9dc9f6;
    &::after {
      content: '';
      background: url('../../assets/images/choose.png');
      position: absolute;
      background-size: 18px 19px;
      top: 50%;
      right: 2%;
      transform: translate(-50%, -50%);
      width: 18px;
      height: 19px;
    }
  }
}

.el-button-isval {
  color: #fff;
  background: #e6a23c;
  border-color: #e6a23c;
}

.el-button-isval-f {
  color: #e6a23c;
  background: #fdf6ec;
  border-color: #f5dab1;
}
.appraised-row {
  padding: 5px;
}
</style>
<style lang="scss">
.table-box th {
  padding: 2px 0;
}
</style>
